//
//  Dialog.swift
//  
//
//  Created by tank on 2021/12/3.
//

import Foundation
import SwiftMessages
import RxSwift

public class Dialog {

    public typealias DialogCompletion = (_ buttonId: String) -> Void

    public static let shared = Dialog()

    private var closeButtonIds: [String: String] = [:]

    private init() {

    }

    public func alert(dialogId: String? = nil,
                      title: String? = nil,
                      message: String,
                      confirmButtonText: String? = nil,
                      interactive: Bool? = nil,
                      completion: DialogCompletion? = nil) {
        dialog(dialogType: .alert,
               dialogId: dialogId,
               title: title,
               message: message,
               confirmButtonText: confirmButtonText,
               interactive: interactive,
               completion: completion)
    }

    public func confirm(dialogId: String? = nil,
                        title: String? = nil,
                        message: String,
                        confirmButtonText: String? = nil,
                        cancelButtonText: String? = nil,
                        interactive: Bool?,
                        completion: DialogCompletion? = nil) {
        dialog(dialogType: .confirm,
               dialogId: dialogId,
               title: title,
               message: message,
               confirmButtonText: confirmButtonText,
               cancelButtonText: cancelButtonText,
               interactive: interactive,
               completion: completion)
    }

    private func dialog(dialogType: DialogView.DialogType,
                        dialogId: String? = nil,
                        title: String? = nil,
                        message: String,
                        confirmButtonText: String? = nil,
                        cancelButtonText: String? = nil,
                        interactive: Bool?,
                        completion: DialogCompletion? = nil) {

        let dialogId = dialogId ?? UUID().uuidString

        let dialogView = DialogView()
        dialogView.set(dialogType: dialogType, dialogId: dialogId, title: title, message: message, confirmButtonText: confirmButtonText)

        var config = SwiftMessages.defaultConfig
        config.presentationStyle = .center
        config.dimMode = .gray(interactive: interactive ?? false)
        config.duration = .forever
        config.interactiveHide = false
        config.eventListeners.append { [weak self] event in
            if event == .didHide, let buttonId = self?.closeButtonIds[dialogId] {
                completion?(buttonId)
            }
        }
        SwiftMessages.show(config: config, view: dialogView)
    }

    public func closeDialog(dialogId: String, buttonId: String) {

        closeButtonIds[dialogId] = buttonId

        SwiftMessages.hide(id: dialogId)
    }
}
